package com.paic.mhis.hcpms.quota.exportword.biz.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.UUIDGenerator;
import com.paic.mhis.hcpms.common.community.dto.MedicalOrgInfoDTO;
import com.paic.mhis.hcpms.common.community.intergration.dao.CommunityDAO;
import com.paic.mhis.hcpms.quota.exportword.biz.service.MakeWordReportJobDetailService;
import com.paic.mhis.hcpms.quota.exportword.dao.WordDataDao;
import com.paic.mhis.hcpms.quota.exportword.dto.KpiBatchDTO;
import com.paic.mhis.hcpms.quota.exportword.dto.KpiLimitDTO;
import com.paic.mhis.hcpms.quota.exportword.itext.CreateRtfTableDataHelper;
import com.paic.mhis.hcpms.quota.exportword.itext.RtfCreatorHelper;
import com.paic.mhis.hcpms.quota.exportword.utils.GeneralMethods;
import com.paic.mhis.hcpms.quota.settlement.common.KpiValueConst;

/**
 * 导出月度分析报告的job启动类
 * 
 * @author: EX-XIONGFEI002
 * @version:
 */
@Service("makeWordReportJobDetailServiceImpl")
public class MakeWordReportJobDetailServiceImpl implements MakeWordReportJobDetailService {

	private static final Logger LOGGER = Logger.getLogger(MakeWordReportJobDetailServiceImpl.class);

	@Value("${rtfReportTemplatePath}")
	private String rtfReportTemplatePath;

	@Value("${isHaveNas}")
	private String isHaveNas;

	@Autowired
	private CommunityDAO communityDao;

	@Autowired
	private CommonDAO commonDao;

	@Autowired
	private WordDataDao wordDataDao;

	@Autowired
	private RtfCreatorHelper rtfCreatorHelper;

	/**
	 * 导出word文件
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void makeWordReportFile() {

		LOGGER.info("makeWordReport job is start ....");

		List<KpiBatchDTO> batchReportList = getBatchReportList();

		for (KpiBatchDTO kpiBatchDTO : batchReportList) {

			Map<String, Object> kpiQuotaLimitMap = getKpiQuotaLimit(kpiBatchDTO.getRegionCode());

			String uuid = UUIDGenerator.get();
			kpiBatchDTO.setTmpBatch("");
			// 更新批次
			if (!this.updateBatchReportStatus(kpiBatchDTO.getId(), "01", uuid, "00")) {
				// 如果有NAS就退出,没有就继续
				if (KpiValueConst.HAVENAS_Y.equals(isHaveNas)) {
					continue;
				}
			} else {
				// 赋值tmpbatch用于入库操作
				kpiBatchDTO.setTmpBatch(uuid);
			}
			// 创建医保月度报告
			rtfCreatorHelper.createMedicarePartyRtf(makeBaseTemplMap(kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);

			// 2、获取筹区域信息
			List<Map> areaCodeList = getAreaCodeList(kpiBatchDTO.getRegionCode());

			for (Map areaCodeDTO : areaCodeList) {

				List<MedicalOrgInfoDTO> queryMedicalOrgInfoList = queryMedicalOrgInfoList(areaCodeDTO);

				// 为每个医院生成一个报告
				for (MedicalOrgInfoDTO medicalOrgInfoDTO : queryMedicalOrgInfoList) {
					//medicalOrgInfoDTO.setMedicalOrgCode("0431");
					// 创建医院月度报告
					rtfCreatorHelper.createHospPartyRtf(medicalOrgInfoDTO, makeBaseTemplMap(kpiBatchDTO),
							kpiQuotaLimitMap, kpiBatchDTO);
					//break;
				}
			}

			// 更新批次状态为成功
			this.updateBatchReportStatus(kpiBatchDTO.getId(), "02", "", "01");
		}

		LOGGER.info("makeWordReport job is end ....");
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List<Map> getAreaCodeList(String regionCode) {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("regionCode", regionCode);

		List<Map> areaCodeList = commonDao.query("Job.getAllAreaInfo", hashMap);

		if (GeneralMethods.getInstance().isEmptyCollects(areaCodeList)) {
			LOGGER.error("can't get araeCode.");
		}

		LOGGER.info("get AreaCode List size is " + areaCodeList.size());

		return areaCodeList;
	}

	/**
	 * 医疗机构列表,只查询三级机构(应该作为入参)
	 * @param regionCodeDTO regionCodeDTO
	 * @return 医疗机构列表
	 */
	@SuppressWarnings("rawtypes")
	private List<MedicalOrgInfoDTO> queryMedicalOrgInfoList(Map regionCodeDTO) {
		// 设置统筹区
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("areaCode", regionCodeDTO.get("codeno"));

		List<MedicalOrgInfoDTO> queryMedicalOrgInfoList = communityDao.queryMedicalOrgInfoListByManpower(paramMap);

		if (GeneralMethods.getInstance().isEmptyCollects(queryMedicalOrgInfoList)) {
			LOGGER.info("not fount org info ,regionCode = " + paramMap.get("regionCode"));
		}

		return queryMedicalOrgInfoList;
	}

	/**
	 * 获取上下限阈值
	 * 
	 * @param areaCodeList
	 *            区域码列表
	 * @return 获取指标阈值
	 */
	private Map<String, Object> getKpiQuotaLimit(String regionCode) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("regionCode", regionCode);

		List<KpiLimitDTO> limitList = wordDataDao.queryKpiRatioLimit(paramMap);

		if (GeneralMethods.getInstance().isEmptyCollects(limitList)) {
			return new HashMap<String, Object>();
		}

		Map<String, Object> kpiQuotaMap = new HashMap<String, Object>();
		for (KpiLimitDTO kpiLimitDTO : limitList) {
			if (GeneralMethods.getInstance().isNotEmptyString(kpiLimitDTO.getKpiCode())
					&& GeneralMethods.getInstance().isNotEmptyString(kpiLimitDTO.getUpperLimit())
					&& GeneralMethods.getInstance().isNotEmptyString(kpiLimitDTO.getLowerLimit())) {
				if ("01".equals(kpiLimitDTO.getValueType())) {
					kpiQuotaMap.put(kpiLimitDTO.getKpiCode() + "_yoy_upper_end", GeneralMethods.getInstance()
							.toFix2Digits(Double.parseDouble(kpiLimitDTO.getUpperLimit())));
					kpiQuotaMap.put(kpiLimitDTO.getKpiCode() + "_yoy_lower_end", GeneralMethods.getInstance()
							.toFix2Digits(Double.parseDouble(kpiLimitDTO.getLowerLimit())));

				} else if ("02".equals(kpiLimitDTO.getValueType())) {
					kpiQuotaMap.put(kpiLimitDTO.getKpiCode() + "_mom_upper_end", GeneralMethods.getInstance()
							.toFix2Digits(Double.parseDouble(kpiLimitDTO.getUpperLimit())));
					kpiQuotaMap.put(kpiLimitDTO.getKpiCode() + "_mom_lower_end", GeneralMethods.getInstance()
							.toFix2Digits(Double.parseDouble(kpiLimitDTO.getLowerLimit())));
				}
			}
		}
		return kpiQuotaMap;
	}

	/**
	 * 查询批次
	 * 
	 * @param areaCodeList
	 *            区域码列表
	 * @return 获取指标阈值
	 */
	private List<KpiBatchDTO> getBatchReportList() {

		LOGGER.info("getBatchReportList start");

		Map<String, String> paramMap = new HashMap<String, String>();
		List<KpiBatchDTO> queryKpiBatchList = wordDataDao.queryKpiBatchList(paramMap);

		if (GeneralMethods.getInstance().isEmptyCollects(queryKpiBatchList)) {
			LOGGER.info("the kpi batch List is empty");
		}
		return queryKpiBatchList;
	}

	/**
	 * 更新
	 * 
	 * @param areaCodeList
	 *            区域码列表
	 * @return 更新
	 */
	private boolean updateBatchReportStatus(String id, String status, String tmp, String preStatus) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("id", id);
		paramMap.put("tmpBatch", tmp);
		paramMap.put("status", status);
		paramMap.put("preStatus", preStatus);

		if (wordDataDao.updateKpiBatchNo(paramMap) <= 0) {
			LOGGER.info("job is running or record is not exist,id = " + id);
			return false;
		}

		LOGGER.info("job is finish,update status with 2,batch_id = " + id);

		return true;
	}

	/**
	 * 全局公共的参数
	 * 
	 * @return map
	 */
	private Map<String, Object> makeBaseTemplMap(KpiBatchDTO kpiBatchDTO) {
		Calendar calendar = Calendar.getInstance();
		Map<String, Object> baseTempl = new HashMap<String, Object>();
		baseTempl.put("now_year", kpiBatchDTO.getKpiTime().split("-")[0]);
		baseTempl.put("now_month", kpiBatchDTO.getKpiTime().split("-")[1]);
		baseTempl.put("current_year", calendar.get(Calendar.YEAR));
		baseTempl.put("current_month", String.valueOf(calendar.get(Calendar.MONTH) + 1));
		baseTempl.put("current_day", String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));

		String pic1 = CreateRtfTableDataHelper.getInstance().getItextImagesPath(rtfReportTemplatePath) + "pic1.png";
		baseTempl.put("k0_1_1_1_totalFee_img_end", pic1);
		baseTempl.put("k0_1_1_2_Fee_Rate_img_end", pic1);
		baseTempl.put("k0_2_1_1_fee_img_end", pic1);
		baseTempl.put("k0_2_1_2_f_img_end", pic1);
		baseTempl.put("k0_2_2_1_Fee_img_end", pic1);
		baseTempl.put("k0_2_2_2_fee_img_end", pic1);
		baseTempl.put("k0_2_3_1_times_img_end", pic1);
		baseTempl.put("k0_2_3_2_fee_img_end", pic1);
		baseTempl.put("k0_2_4_1_days_img_end", pic1);
		baseTempl.put("k0_2_4_2_fee_img_end", pic1);
		baseTempl.put("k0_3_1_1_fee_img_end", pic1);
		baseTempl.put("k0_3_1_2_fee_Rate_img_end", pic1);
		baseTempl.put("k0_3_2_1_fee_img_end", pic1);
		baseTempl.put("k0_3_2_2_fee_img_end", pic1);
		baseTempl.put("k0_3_3_1_times_img_end", pic1);
		baseTempl.put("k0_3_3_2_fee_img_end", pic1);
		baseTempl.put("k0_3_4_1_times_img_end", pic1);
		baseTempl.put("k0_3_4_2_fee_img_end", pic1);
		baseTempl.put("k2_1_1_1_totalFee_img_end", pic1);
		baseTempl.put("k2_1_1_2_fee_Rate_img_end", pic1);
		baseTempl.put("k2_2_1_1_fee_img_end", pic1);
		baseTempl.put("k2_2_1_2_f_img_end", pic1);
		baseTempl.put("k2_2_2_1_Fee_img_end", pic1);
		baseTempl.put("k2_2_2_2_fee_img_end", pic1);
		baseTempl.put("k2_2_3_1_times_img_end", pic1);
		baseTempl.put("k2_2_3_2_fee_img_end", pic1);
		baseTempl.put("k2_2_4_1_days_img_end", pic1);
		baseTempl.put("k2_2_4_2_fee_img_end", pic1);
		baseTempl.put("k2_3_1_1_fee_img_end", pic1);
		baseTempl.put("k2_3_1_2_f_img_end", pic1);
		baseTempl.put("k2_3_2_1_Fee_img_end", pic1);
		baseTempl.put("k2_3_2_2_fee_img_end", pic1);
		baseTempl.put("k2_3_3_1_times_img_end", pic1);
		baseTempl.put("k2_3_3_2_fee_img_end", pic1);
		baseTempl.put("k2_3_4_1_days_img_end", pic1);
		baseTempl.put("k2_3_4_2_fee_img_end", pic1);

		return baseTempl;
	}

	public String getIsHaveNas() {
		return isHaveNas;
	}

	public void setIsHaveNas(String isHaveNas) {
		this.isHaveNas = isHaveNas;
	}

}
